package com.suoluo.zenadmin.controllers.admin;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Intercepted;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;

import com.suoluo.zenadmin.common.CommonResp;
import com.suoluo.zenadmin.common.encrypt.EncryptUtil;
import com.suoluo.zenadmin.controllers.JSONInterceptor.JSON;
import com.suoluo.zenadmin.service.user.AdminService;
import com.suoluo.zenadmin.vo.user.UserVO;

@Path("/")
public class AdminController {
	
	@Resource(name="adminService")
	private AdminService adminService;
	
	@Get("/")
	public String main(){
		return "layout";
	}
	
	@Intercepted(deny="login")
	@Post("login")
	public String login(Invocation inv) throws Exception {
		HttpServletRequest req = inv.getRequest();
		String username = req.getParameter("username").trim();
		String password = req.getParameter("password").trim();
		String randomCode = req.getParameter("randomCode").trim();
		String temp = (String) req.getSession().getAttribute("RANDOMVALIDATECODEKEY");
		req.getSession().removeAttribute("RANDOMVALIDATECODEKEY");
		randomCode = randomCode.toUpperCase();
		UserVO user = null;
		if(randomCode.equals(temp))
		{
			 user = adminService.findUser(username,EncryptUtil.md5(password));	
		}
		if(user != null)
		{
			AdminLoginManager.login(inv, username);
			AdminLoginManager.isDelete(inv,user.getIsDelete());
			return "r:"+inv.getRequestPath().getCtxpath()+"/admin/";
		}
		else 
		{
			return "login";
		}
	}
	
	@Intercepted(deny="login")
	@Get("login")
	public String showLogin(Invocation inv){
		if (AdminLoginManager.isLogined(inv)){
			return "layout";
		}else{
			return "login";
		}
	}
	
	@Intercepted(deny="login")
	public void verifyCode(Invocation invo) throws Exception { 
		HttpServletResponse resp = invo.getResponse();
		HttpServletRequest req = invo.getRequest();
		resp.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图�?
		resp.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
		resp.setHeader("Cache-Control", "no-cache");
		resp.setDateHeader("Expire", 0);
        RandomValidateCode randomValidateCode = new RandomValidateCode();
        try {
            randomValidateCode.getRandcode(req,resp);//输出图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	
	@Intercepted(deny="login")
	@JSON
	@Get("nodelete")
	public Object noDelete(Invocation inv){
		CommonResp resp = new CommonResp();
		resp.setResultCode(CommonResp.FAIL_CODE);
		resp.setResultMsg("您没有删除权限，不可以执行删除操作！");
		return resp;
	}
}
